package com.sunagy.demand.backend.aspect;

import com.sunagy.demand.backend.exception.TokenNoneException;
import com.sunagy.demand.backend.security.SecurityUserDetails;
import com.sunagy.demand.backend.service.AdminAuthTokenService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * desc：#Admin的切面认证
 * author：三餘無夢生
 * date：2018/4/25
 * time：下午1:52
 */
@Aspect
@Component
@Slf4j
public class AdminAuthorizeAspect {

    @Autowired
    private AdminAuthTokenService adminAuthTokenService;

    @Pointcut("execution(public * com.sunagy.demand.backend.controller.*.*(..))"  +
    "&& !execution(public * com.sunagy.demand.backend.controller.AdminUserController.login(..))")
    public void verify(){

    };

    @Before("verify()")
    public void doVerify(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //这里从url参数获取，也可以从cookie或者header里面获取
        String token = request.getHeader("Authorization");
        if (token == null){
            log.warn("【token校验】url参数中找不到token");
            throw new TokenNoneException();
        }
        //去数据库中查询token并做过期校验,把userid放到header中
        SecurityUserDetails securityUserDetails = adminAuthTokenService.validToken(token);
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(securityUserDetails,null));

    }
}
